#include "StaticAlgorithm.h"
#include "../RSTController.h"
#include "Utils.h"
#include <sstream>

namespace RafMat
{
namespace SimEngine
{

using namespace std;
using namespace SimInterface;

StaticAlgorithm::StaticAlgorithm(RSTController& owner)
    : AdaptiveAlgorithmBase(owner, "static", "UserRST")
{
}

void StaticAlgorithm::adapt(double ctrlVar, double processVar, double setPoint)
{
    // Zapobieżenie ostrzeżeniom kompilatora
    (void) ctrlVar;
    (void) processVar;
    (void) setPoint;

    // Nie rób po prostu nic.
}

//
// Konfiguracja parametrów z poziomu GIU
//

bool StaticAlgorithm::setParameter(const string& param, const string& value) throw(std::logic_error)
{
    // Usuń ewentualne wiodące i końcowe spacje
    string tparam = Utils::trimWhiteSpaces(param);
    string tvalue = Utils::trimWhiteSpaces(value);

    // Strumień danych dla łańcucha argumentu.
    istringstream istr(tvalue);

    bool success = true;

    if(tparam == CONF_RPOLY)
    {
        Polynomial poly = Polynomial(Utils::convertStrToVector(tvalue, /* out */ success));
        if(success)
        {
            m_r = poly;
            this->getOwner().resizeBuffersIfNecessary();
        }
    }
    else if(tparam == CONF_SPOLY)
    {
        Polynomial poly = Polynomial(Utils::convertStrToVector(tvalue, /* out */ success));
        if(success)
        {
            m_s = poly;
            this->getOwner().resizeBuffersIfNecessary();
        }
    }
    else if(tparam == CONF_TPOLY)
    {
        Polynomial poly = Polynomial(Utils::convertStrToVector(tvalue, /* out */ success));
        if(success)
        {
            m_t = poly;
            this->getOwner().resizeBuffersIfNecessary();
        }
    }
    else if(param == CONF_H)
    {
        int tmpH;
        istr >> tmpH;
        if(!istr.bad())
        {
            m_h = tmpH;
        }
    }
    else
        throw iconf_error::unrecognizedParam(*this, tparam);

    if(istr.bad() || !success)
        throw iconf_error::syntaxError(*this, tvalue);

    return true;
}

SimFile::ConfigWriter& StaticAlgorithm::dumpParameters(SimFile::ConfigWriter& o) const
{
    o.pushParam("adpt::" + CONF_RPOLY, m_r);
    o.pushParam("adpt::" + CONF_SPOLY, m_s);
    o.pushParam("adpt::" + CONF_TPOLY, m_t);
    o.pushParam("adpt::" + CONF_H, m_h);
    return o;
}

}
}
